package nju.software.xkxt.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nju.software.xkxt.biz.vo.CourseVO;
import nju.software.xkxt.biz.vo.LoginVO;
import nju.software.xkxt.biz.vo.SelectionVO;
import nju.software.xkxt.biz.vo.UserVO;
import nju.software.xkxt.service.CourseService;
import nju.software.xkxt.service.ScoreService;
import nju.software.xkxt.service.SelectionService;
import nju.software.xkxt.service.UserService;
import nju.software.xkxt.service.convertor.UserConvertor;
import nju.software.xkxt.service.model.CourseModel;
import nju.software.xkxt.service.model.ScoreModel;
import nju.software.xkxt.service.model.SelectionModel;
import nju.software.xkxt.service.model.UserContextModel;
import nju.software.xkxt.service.model.UserModel;
import nju.software.xkxt.web.json.ResponseBuilder;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author typ
 * 
 */
@Controller
public class UserController {
	UserService userService;
	SelectionService selectionService;
	CourseService courseService;
	ScoreService scoreService;

	/**
	 * 跳转到主页面
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/main.do", method = RequestMethod.GET)
	public String showMain(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		return "login";
	}

	/**
	 * 获取登陆信息，判断登陆是否成功，成功则跳转，不成功返回出错信息
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {
		String sch_num = request.getParameter("schoolNo");
		String passwd = request.getParameter("password");
		boolean b = userService.vertifyUser(sch_num, passwd);
		UserModel userModel = userService.getUserBySchoolNo(sch_num);
		if (b) {
			UserContextModel userContextModel = new UserContextModel(userModel);
			request.getSession().setAttribute("userContextModel",
					userContextModel);
		}
		String role = String.valueOf(userModel.getRole());
		ResponseBuilder responseBuilder = new ResponseBuilder();
		LoginVO loginVO = new LoginVO();
		loginVO.setSuccess(b);
		loginVO.setName(sch_num);
		loginVO.setRole(role);
		try {
			responseBuilder.writeJsonResponse(response, loginVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加一条user
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/register.do", method = RequestMethod.GET)
	public String showRegister(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		return "register";
	}

	/**
	 * 添加一条user
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
	public void addUser(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		String name = request.getParameter("name");
		String schoolNo = request.getParameter("schoolNo");
		String pwd = request.getParameter("pwd");
		String sex = request.getParameter("sex");
		String role = request.getParameter("role");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		UserVO userVO = new UserVO();
		userVO.setEmail(email);
		userVO.setName(name);
		userVO.setPhone(phone);
		userVO.setPwd(pwd);
		userVO.setRole(role);
		userVO.setSchoolNo(schoolNo);
		userVO.setSex(sex);
		UserModel userModel = new UserModel();
		userModel = UserConvertor.voToModel(userVO);
		boolean isSuccess = userService.addUser(userModel);
		ResponseBuilder responseBuilder = new ResponseBuilder();
		try {
			responseBuilder.writeJsonResponse(response, isSuccess);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 显示选课信息
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/select.do", method = RequestMethod.GET)
	public String select(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		List<SelectionVO> selectionVOs = new ArrayList<SelectionVO>();

		UserContextModel userContextModel = (UserContextModel) request
				.getSession().getAttribute("userContextModel");
		String yhm = userContextModel.getName();
		map.addAttribute("yhm", yhm);
		int userId = userContextModel.getUserId();
		map.addAttribute("uid", String.valueOf(userId));
		List<SelectionModel> selectionModels = selectionService
				.getSelectionModelByUserId(userId);
		for (SelectionModel selectionModel : selectionModels) {
			SelectionVO selectionVO = new SelectionVO(selectionModel);
			selectionVOs.add(selectionVO);
		}
		map.addAttribute("selectionVOs", selectionVOs);
		return "courseselect";
	}

	/**
	 * 学生提交选课结果
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/selectCourses.do", method = RequestMethod.POST)
	public String getSelectionList(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String courseId[] = request.getParameterValues("courseId[]");
		String isChecked[] = request.getParameterValues("checkedValue[]");
		UserContextModel userContextModel = (UserContextModel) request
				.getSession().getAttribute("userContextModel");
		Map<Integer, Integer> checkMap = new HashMap<Integer, Integer>();
		if (courseId.length != isChecked.length)
			return "redirect:/select.do";

		int i = 0;
		for (String cid : courseId) {
			checkMap.put(Integer.valueOf(cid), Integer.valueOf(isChecked[i]));
			i++;
		}
		boolean b = selectionService.updateSelectionModelByUserId(
				userContextModel.getUserId(), checkMap);

		if (b)
			return "redirect:/select.do";
		else {
			return "redirect:/select.do";
		}
	}

	/**
	 * 学生确定最终提交选课结果
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/confirmSelection.do", method = RequestMethod.POST)
	public void confirmSelect(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String uid = request.getParameter("uid");

		List<SelectionModel> selectionModels = selectionService
				.getSelectionModelByUserId(Integer.valueOf(uid));
		List<ScoreModel> scoreModels = new ArrayList<ScoreModel>();
		for (SelectionModel src : selectionModels) {
			if (src.getState() == 1) {
				ScoreModel scoreModel = new ScoreModel(src);
				scoreModels.add(scoreModel);
			}
		}
		int num = scoreService.addScore(scoreModels);
		String state=String.valueOf(num);
		ResponseBuilder responserBuilder = new ResponseBuilder();
		try {
			responserBuilder.writeJsonResponse(response, state);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回管理员登陆的主页面
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/adminSelect.do", method = RequestMethod.GET)
	public String adminselect(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		List<SelectionVO> selectionVOs = new ArrayList<SelectionVO>();

		UserContextModel userContextModel = (UserContextModel) request
				.getSession().getAttribute("userContextModel");
		String yhm = userContextModel.getName();
		map.addAttribute("yhm", yhm);
		int userId = userContextModel.getUserId();
		List<SelectionModel> selectionModels = selectionService
				.getSelectionModelByUserId(userId);
		for (SelectionModel selectionModel : selectionModels) {
			SelectionVO selectionVO = new SelectionVO(selectionModel);
			selectionVOs.add(selectionVO);
		}
		map.addAttribute("selectionVOs", selectionVOs);
		return "adminhome";

	}

	/**
	 * 管理员修改密码时候验证原密码是否正确
	 * 
	 * @param request
	 * @param response
	 * @param map
	 */
	@RequestMapping(value = "/vertify.do", method = RequestMethod.POST)
	public void vertifyPwd(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		String passwd = request.getParameter("pwd");
		boolean b = userService.vertifyPwd(passwd);
		ResponseBuilder responseBuilder = new ResponseBuilder();
		try {
			responseBuilder.writeJsonResponse(response, b);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 管理员修改密码
	 * 
	 * @param request
	 * @param response
	 * @param map
	 */
	@RequestMapping(value = "/alterpwd.do", method = RequestMethod.POST)
	public void alterPwd(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		String new_pwd = request.getParameter("new_pwd");
		boolean b = userService.alterPwd(new_pwd);
		ResponseBuilder responseBuilder = new ResponseBuilder();
		try {
			responseBuilder.writeJsonResponse(response, b);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获取学生或者老师列表
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/userList.do", method = RequestMethod.GET)
	public String getUserList(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		UserContextModel userContextModel = (UserContextModel) request
				.getSession().getAttribute("userContextModel");
		String yhm = userContextModel.getName();
		map.addAttribute("yhm", yhm);
		String rolesString = request.getParameter("role");
		int role = Integer.valueOf(rolesString);
		List<UserVO> userVOs = new ArrayList<UserVO>();
		List<UserModel> userModels = userService.getUserByRole(role);
		for (UserModel userModel : userModels) {
			UserVO userVO = new UserVO(userModel);
			userVOs.add(userVO);
		}
		map.addAttribute("userList", userVOs);
		if (role == 0) {
			return "teacherlist";
		} else if (role == 1) {
			return "studentlist";
		} else {
			return "error";
		}
	}

	/**
	 * 获取课程列表
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/courseList.do", method = RequestMethod.GET)
	public String courseList(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		UserContextModel userContextModel = (UserContextModel) request
				.getSession().getAttribute("userContextModel");
		String yhm = userContextModel.getName();
		map.addAttribute("yhm", yhm);
		List<CourseVO> courseVOs = new ArrayList<CourseVO>();
		List<CourseModel> courseModels = courseService.getCourse();
		for (CourseModel courseModel : courseModels) {
			CourseVO courseVO = new CourseVO(courseModel);
			courseVOs.add(courseVO);
		}
		map.addAttribute("courseList", courseVOs);
		return "courselist";

	}

	/**
	 * 获取选课列表
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/selectList.do", method = RequestMethod.GET)
	public String selectList(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		UserContextModel userContextModel = (UserContextModel) request
				.getSession().getAttribute("userContextModel");
		String yhm = userContextModel.getName();
		map.addAttribute("yhm", yhm);
		List<SelectionVO> selectionVOs = new ArrayList<SelectionVO>();
		List<SelectionModel> selectionModels = selectionService.getSelection();
		for (SelectionModel selectionModel : selectionModels) {
			SelectionVO selectionVO = new SelectionVO(selectionModel);
			selectionVOs.add(selectionVO);
		}
		map.addAttribute("selectList", selectionVOs);
		return "selectlist";

	}

	/**
	 * 根据userId来删除老师或者学生记录
	 * 
	 * @param request
	 * @param response
	 * @param map
	 */
	@RequestMapping(value = "/userDelete.do", method = RequestMethod.POST)
	public void userDelete(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		String id = request.getParameter("userId");
		int userId = Integer.valueOf(id);
		boolean isSuccess = userService.deleteById(userId);
		ResponseBuilder responseBuilder = new ResponseBuilder();
		try {
			responseBuilder.writeJsonResponse(response, isSuccess);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据courseId来删除一条课程记录
	 * 
	 * @param request
	 * @param response
	 * @param map
	 */
	@RequestMapping(value = "/courseDelete.do", method = RequestMethod.POST)
	public void courseDelete(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		String id = request.getParameter("courseId");
		int courseId = Integer.valueOf(id);
		boolean isSuccess = courseService.delete(courseId);
		ResponseBuilder responseBuilder = new ResponseBuilder();
		try {
			responseBuilder.writeJsonResponse(response, isSuccess);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据courseId来删除一条选课的课程记录
	 * 
	 * @param request
	 * @param response
	 * @param map
	 */
	@RequestMapping(value = "/selectDelete.do", method = RequestMethod.POST)
	public void selectDelete(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		String id = request.getParameter("courseId");
		int courseId = Integer.valueOf(id);
		boolean isSuccess = selectionService.delete(courseId);
		ResponseBuilder responseBuilder = new ResponseBuilder();
		try {
			responseBuilder.writeJsonResponse(response, isSuccess);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setSelectionService(SelectionService selectionService) {
		this.selectionService = selectionService;
	}

	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	public void setScoreService(ScoreService scoreService) {
		this.scoreService = scoreService;
	}

}
